// 初始化图表
let dynagraphChart = echarts.init(document.getElementById('dynagraphChart'));

// 不同工况的示功图数据（增加更多故障工况）
const dynagraphData = {
    normal: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [40, 45, 50, 55, 60, 58, 52, 48, 45, 50, 55, 60, 65, 62, 58, 52, 40],
        description: "正常工况：示功图形状规则，载荷变化平稳"
    },
    gas: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [35, 38, 42, 45, 48, 52, 50, 45, 40, 48, 55, 60, 65, 62, 58, 52, 35],
        description: "气体影响：上冲程载荷降低，图形呈现气锁特征"
    },
    leak: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [30, 35, 40, 42, 45, 48, 45, 40, 35, 45, 52, 58, 62, 60, 55, 48, 30],
        description: "凡尔漏失：载荷差减小，泵效降低"
    },
    pumpTrouble: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [25, 30, 40, 50, 70, 65, 55, 45, 35, 50, 65, 75, 85, 80, 70, 55, 25],
        description: "泵故障：载荷异常波动，图形不规则"
    },
    rodBreak: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20],
        description: "抽油杆断脱：载荷几乎不变，失去泵抽作用"
    },
    wax: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [45, 50, 58, 65, 75, 70, 62, 55, 48, 55, 65, 72, 80, 75, 68, 58, 45],
        description: "结蜡工况：载荷整体增大，摩擦阻力增加"
    },
    drift: {
        displacement: [0, 0.5, 1, 1.5, 2, 1.5, 1, 0.5, 0, -0.5, -1, -1.5, -2, -1.5, -1, -0.5, 0],
        load: [50, 55, 60, 65, 70, 68, 62, 58, 55, 60, 65, 70, 75, 72, 68, 62, 50],
        description: "载荷漂移：示功图整体偏移，需要校正"
    }
};

// 工况诊断结果
const diagnosisResults = {
    normal: { text: "正常工况", canCalculate: true },
    gas: { text: "气体影响", canCalculate: true },
    leak: { text: "凡尔漏失", canCalculate: false, alert: "油管漏失，不能进行动液面折算" },
    pumpTrouble: { text: "泵故障", canCalculate: true },
    rodBreak: { text: "抽油杆断脱", canCalculate: false, alert: "抽油杆断脱，不能进行动液面折算" },
    wax: { text: "结蜡工况", canCalculate: true },
    drift: { text: "载荷漂移", canCalculate: true }
};

// 图表配置
const chartOption = {
    title: {
        text: '示功图分析',
        left: 'center'
    },
    tooltip: {
        trigger: 'axis',
        formatter: function(params) {
            return `位移: ${params[0].value[0].toFixed(2)} m<br>载荷: ${params[0].value[1].toFixed(2)} kN`;
        }
    },
    xAxis: {
        type: 'value',
        name: '位移 (m)',
        min: -2.5,
        max: 2.5
    },
    yAxis: {
        type: 'value',
        name: '载荷 (kN)',
        min: 15,
        max: 90
    },
    series: [{
        type: 'line',
        smooth: true,
        data: [],
        lineStyle: {
            width: 3,
            color: '#1890ff'
        },
        itemStyle: {
            color: '#1890ff',
            opacity: 0.8
        },
        areaStyle: {
            color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [{
                    offset: 0, color: 'rgba(24, 144, 255, 0.3)'
                }, {
                    offset: 1, color: 'rgba(24, 144, 255, 0.1)'
                }]
            }
        }
    }]
};

// 计算功图面积
function calculateArea(displacement, load) {
    let area = 0;
    for (let i = 1; i < displacement.length; i++) {
        area += (load[i] + load[i-1]) * (displacement[i] - displacement[i-1]) / 2;
    }
    return Math.abs(area);
}

// 载荷校正函数 - 根据流程图中的校正步骤
function correctLoadData(condition, displacement, load) {
    let correctedLoad = [...load];
    
    // 漂移载荷校正
    if (condition === 'drift') {
        const averageLoad = load.reduce((a, b) => a + b, 0) / load.length;
        const correction = 45 - averageLoad; // 假设正常平均载荷为45kN
        correctedLoad = load.map(l => l + correction);
    }
    
    // 结蜡载荷校正
    if (condition === 'wax') {
        const maxLoad = Math.max(...load);
        if (maxLoad > 70) {
            const correctionFactor = 70 / maxLoad;
            correctedLoad = load.map(l => l * correctionFactor);
        }
    }
    
    return correctedLoad;
}

// 基于力学模型的动液面计算
function calculateFluidLevelByMechanicalModel(displacement, load) {
    // 根据第二张图片中的力学模型
    // 光杆载荷 = 抽油杆在油中的重量 + 活塞截面以上液柱重量 ± 惯性载荷
    
    const maxLoad = Math.max(...load);
    const minLoad = Math.min(...load);
    const loadDifference = maxLoad - minLoad;
    
    // 简化力学模型公式
    // 动液面深度 ≈ (最大载荷 - 杆柱重量) / (液体密度 × 重力加速度 × 活塞面积)
    
    // 模拟参数（实际应用中这些是已知的）
    const rodWeightInFluid = 25; // 抽油杆在油中的重量 (kN)
    const fluidDensity = 850;    // 液体密度 (kg/m³)
    const pistonArea = 0.01;     // 活塞截面积 (m²)
    const g = 9.8;              // 重力加速度
    
    // 计算液柱重量产生的载荷
    const fluidColumnLoad = maxLoad - rodWeightInFluid;
    
    // 计算动液面深度
    const fluidLevel = fluidColumnLoad / (fluidDensity * g * pistonArea * 0.001); // 转换为米
    
    return Math.max(200, Math.min(1500, Math.round(fluidLevel)));
}

// 功图量油计算
function calculateLiquidProduction(condition, displacement, load) {
    const area = calculateArea(displacement, load);
    
    // 基于功图面积和泵效的计算模型
    let production = 0;
    let efficiency = 0;
    
    switch(condition) {
        case 'normal':
            efficiency = 0.85;
            production = area * 15.8 * efficiency;
            break;
        case 'gas':
            efficiency = 0.65;
            production = area * 15.8 * efficiency;
            break;
        case 'leak':
            efficiency = 0.35;
            production = area * 15.8 * efficiency;
            break;
        case 'pumpTrouble':
            efficiency = 0.25;
            production = area * 15.8 * efficiency;
            break;
        case 'rodBreak':
            efficiency = 0.05;
            production = area * 15.8 * efficiency;
            break;
        case 'wax':
            efficiency = 0.55;
            production = area * 15.8 * efficiency;
            break;
        case 'drift':
            efficiency = 0.75;
            production = area * 15.8 * efficiency;
            break;
    }
    
    // 加入合理波动
    const fluctuation = 1 + (Math.random() * 0.2 - 0.1); // ±10%波动
    return {
        production: Math.round(production * fluctuation),
        efficiency: Math.round(efficiency * 100)
    };
}

// 更新图表
function updateChart(condition) {
    const data = dynagraphData[condition];
    const points = [];
    
    for (let i = 0; i < data.displacement.length; i++) {
        points.push([data.displacement[i], data.load[i]]);
    }
    
    chartOption.series[0].data = points;
    chartOption.title.text = `示功图分析 - ${diagnosisResults[condition].text}`;
    dynagraphChart.setOption(chartOption);
    
    // 更新工况描述
    document.getElementById('conditionDescription').textContent = data.description;
}

// 主要计算函数 - 按照流程图顺序执行
function calculateParameters(condition) {
    const originalData = dynagraphData[condition];
    let displacement = originalData.displacement;
    let load = originalData.load;
    
    // 1. 工况诊断
    const diagnosis = diagnosisResults[condition];
    document.getElementById('diagnosisResult').textContent = diagnosis.text;
    document.getElementById('diagnosisResult').className = diagnosis.canCalculate ? 'text-success' : 'text-danger';
    
    // 2. 检查是否故障工况（断脱、漏失）
    if (!diagnosis.canCalculate) {
        document.getElementById('liquidProduction').textContent = '--';
        document.getElementById('fluidLevel').textContent = '--';
        document.getElementById('pumpEfficiency').textContent = '--';
        document.getElementById('calculationAlert').textContent = diagnosis.alert;
        document.getElementById('calculationAlert').style.display = 'block';
        return;
    }
    
    document.getElementById('calculationAlert').style.display = 'none';
    
    // 3. 载荷校正处理
    const correctedLoad = correctLoadData(condition, displacement, load);
    
    // 4. 功图量油计算
    const productionResult = calculateLiquidProduction(condition, displacement, correctedLoad);
    document.getElementById('liquidProduction').textContent = productionResult.production;
    document.getElementById('pumpEfficiency').textContent = productionResult.efficiency;
    
    // 5. 动液面计算（基于力学模型）
    const fluidLevel = calculateFluidLevelByMechanicalModel(displacement, correctedLoad);
    document.getElementById('fluidLevel').textContent = fluidLevel;
    
    // 显示计算过程
    showCalculationProcess(condition, originalData.load, correctedLoad);
    
    return { 
        production: productionResult.production, 
        fluidLevel: fluidLevel, 
        efficiency: productionResult.efficiency 
    };
}

// 显示计算过程
function showCalculationProcess(condition, originalLoad, correctedLoad) {
    const processElement = document.getElementById('calculationProcess');
    let processText = '';
    
    if (condition === 'drift') {
        const originalAvg = originalLoad.reduce((a, b) => a + b, 0) / originalLoad.length;
        const correctedAvg = correctedLoad.reduce((a, b) => a + b, 0) / correctedLoad.length;
        processText = `漂移校正: 平均载荷 ${originalAvg.toFixed(1)}kN → ${correctedAvg.toFixed(1)}kN`;
    } else if (condition === 'wax') {
        const originalMax = Math.max(...originalLoad);
        const correctedMax = Math.max(...correctedLoad);
        processText = `结蜡校正: 最大载荷 ${originalMax.toFixed(1)}kN → ${correctedMax.toFixed(1)}kN`;
    } else {
        processText = '数据正常，无需校正';
    }
    
    processElement.textContent = processText;
    processElement.style.display = 'block';
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始显示正常工况
    updateChart('normal');
    document.getElementById('diagnosisResult').textContent = diagnosisResults.normal.text;
    
    // 工况选择事件
    document.getElementById('workingCondition').addEventListener('change', function() {
        const condition = this.value;
        updateChart(condition);
        document.getElementById('diagnosisResult').textContent = diagnosisResults[condition].text;
        document.getElementById('diagnosisResult').className = diagnosisResults[condition].canCalculate ? 'text-success' : 'text-danger';
        
        // 重置计算结果
        document.getElementById('liquidProduction').textContent = '--';
        document.getElementById('fluidLevel').textContent = '--';
        document.getElementById('pumpEfficiency').textContent = '--';
        document.getElementById('calculationAlert').style.display = 'none';
        document.getElementById('calculationProcess').style.display = 'none';
    });
    
    // 分析按钮事件
    document.getElementById('analyzeBtn').addEventListener('click', function() {
        const condition = document.getElementById('workingCondition').value;
        const diagnosis = diagnosisResults[condition];
        
        let alertMessage = `工况分析完成！\n诊断结果：${diagnosis.text}`;
        if (!diagnosis.canCalculate) {
            alertMessage += `\n⚠️ ${diagnosis.alert}`;
        }
        
        alert(alertMessage);
    });
    
    // 计算按钮事件
    document.getElementById('calculateBtn').addEventListener('click', function() {
        const condition = document.getElementById('workingCondition').value;
        calculateParameters(condition);
    });
    
    // 窗口大小变化时重绘图表
    window.addEventListener('resize', function() {
        dynagraphChart.resize();
    });
});